package com.zhangwei.day38.dao.impl;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhangwei.day38.bean.User;
import com.zhangwei.day38.dao.DbBean;
import com.zhangwei.day38.dao.IUserDao;
import com.zhangwei.day38.dao.UserSqliteOpenHelper;

import java.util.List;

/**
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.zhangwei.day38.dao
 * @Description:
 * @date 15/10/20 下午2:27
 */

public class UserDaoImpl implements IUserDao {
    private UserSqliteOpenHelper helper;


    public UserDaoImpl() {
        this.helper = new UserSqliteOpenHelper();
    }

    @Override
    public void save(User user) {
        // 以读写的方式打开数据
        SQLiteDatabase database = helper.getReadableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", user.getName());
        contentValues.put("pwd", user.getPwd());
        database.insert(DbBean.UserDb.TAB_NAME, null, contentValues);
        database.close();
        //以写的方式打开数据
//        helper.getWritableDatabase();


    }

    @Override
    public User find(long id) {
        User user = null;
        SQLiteDatabase database = helper.getReadableDatabase();
        String sql = "select * from " + DbBean.UserDb.TAB_NAME + "where id=" + id;
        Cursor cursor = database.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            user = new User(cursor);
        }


        return user;
    }

    @Override
    public void saveAll(List<User> list) {
        SQLiteDatabase database = helper.getReadableDatabase();
        database.beginTransaction();
        for (User user : list){
            save(user);
        }
        database.endTransaction();
    }
}
